<?php


namespace App\Libs;


/**
 * 助手类
 *
 * Class Help
 *
 * @package App\Libs
 */
class Help
{
    private function __construct() {}

    private function __clone() {}


    /**
     * 监听SQL语句
     */
    public static function printSql()
    {
        \Illuminate\Support\Facades\DB::listen(function ($query) {

            $bindings = $query->bindings;
            $sql = $query->sql;

            foreach ($bindings as $replace){
                $value = is_numeric($replace) ? $replace : "'".$replace."'";
                $sql = preg_replace('/\?/', $value, $sql, 1);
            }

            echo($sql) . "\r\n";
        });
    }

    /**
     * 获取随机数
     *
     * @param int $len
     * @param string|null $chars
     *
     * @return string
     */
    public static function getRandomString(int $len, string $chars = null)
    {
        // 密码字符集，可任意添加你需要的字符
        if ($chars === null){
            $chars = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        }

        // 在 $chars 中随机取 $length 个数组元素键名
        $keys = array_rand($chars, $len);
        $str = '';
        for($i = 0; $i < $len; $i++) {
            // 将 $length 个数组元素连接成字符串
            $str .= $chars[$keys[$i]];
        }

        return $str;
    }
}
